function Prob = myOptimFun_2attractor(P,x,ind_optim,ind_actinh,ind_data,G,fName_mismatch,fName_iter_tmp)
%% optimization function for the genetic algorithm
%load iteration_tmp
iter = importdata(fName_iter_tmp);

P = round(P);
% Pre-filtering solutions and removing no reaction case
if all(P(1:numel(ind_optim)) == 0)
    Prob = Inf;
    return;
end

% Set adjacency matrix
G1 = G;
G1(ind_actinh(~~P(numel(ind_optim)+1:end))) = 1;
G1(ind_actinh(~P(numel(ind_optim)+1:end))) = -1;
G1(ind_optim(~P(1:numel(ind_optim)))) = 0;


% Mismatch matrix
try
    % Compute attractor from the initial expression state
    [Att_states1,count1] = boolSim_(G1,x(:,1),1000);
    val1 = sum(abs(Att_states1(ind_data,1)-x(ind_data,1)));   
	% Compute attractor from the final expression state	
    [Att_states2,count2] = boolSim_(G1,x(:,2),1000);
    val2 = sum(abs(Att_states2(ind_data,1)-x(ind_data,2)));

    % Penalty if both attractors are same
    if all(Att_states1 == Att_states2)
        Prob = 2*(iter)*max(val1,val2)/size(x,1);
     elseif count1 > 1000 || count2 > 1000  %after 2000 boolean simulations
        Prob = 10*(iter)*max(val1,val2)/size(x,1);
     else
        Prob = (iter)*max(val1,val2)/size(x,1);
    end
catch
    Prob = Inf;    
    display('error');
    return;
end
dlmwrite(fName_mismatch, [iter Prob val1 val2 count1 count2 val1+val2 P],'-append','delimiter',' ','newline','pc');

end
